﻿using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace TransformerManager.API.Utils
{
    public class JwtSetting
    {
        public SigningCredentials SigningCredentials;

        public string Issuer;

        public string Audience;

        public DateTime Expires;

        public ClaimsIdentity Subject;

        private readonly IConfiguration _configuration;

        public JwtSetting(IConfiguration configuration)
        {
            _configuration = configuration;
            // 创建JWT
            // 定义编码算法
            var signingAlgorithm = SecurityAlgorithms.HmacSha256;

            // Token的身份证，类似一个人可以有身份证，户口本
            Subject = new ClaimsIdentity(new[]
            {
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString("N")),
                new Claim(JwtRegisteredClaimNames.Sub, "userId") // 可以创建多个
            });

            // signiture
            // signingKey的内容必须是16个字符串以上，否则报System.ArgumentOutOfRangeException错误
            var secretByte = Encoding.UTF8.GetBytes(_configuration["Authenticatiton:SecretKey"]);
            var signingKey = new SymmetricSecurityKey(secretByte);

            SigningCredentials = new SigningCredentials(signingKey, signingAlgorithm);
            Issuer = _configuration["Authenticatiton:Issuer"];
            Audience = _configuration["Authenticatiton:Audience"];
            Expires = DateTime.UtcNow.AddHours(8);
        }
    }
}
